/*
 *    Copyright (c) 2018-2025, haohanwork.com All rights reserved.
 */
package com.haohan.cloud.scm.saleb.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haohan.cloud.scm.api.constant.ScmCacheNameConstant;
import com.haohan.cloud.scm.api.saleb.entity.Buyer;
import com.haohan.cloud.scm.api.saleb.req.CountBuyerNumReq;
import com.haohan.cloud.scm.saleb.mapper.BuyerMapper;
import com.haohan.cloud.scm.saleb.service.BuyerService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

/**
 * 采购商
 *
 * @author haohan
 * @date 2019-05-13 20:35:22
 */
@Service
@AllArgsConstructor
public class BuyerServiceImpl extends ServiceImpl<BuyerMapper, Buyer> implements BuyerService {

    private final BuyerMapper buyerMapper;

    @Override
    public boolean save(Buyer entity) {
        entity.setId(null);
        entity.setTenantId(null);
        return retBool(baseMapper.insert(entity));
    }

    @Override
    @Caching(evict = {
            @CacheEvict(value = ScmCacheNameConstant.WECHAT_BUYER_INFO, key = "#entity.passportId", condition = "#entity.passportId != null"),
            @CacheEvict(value = ScmCacheNameConstant.MANAGE_PRICING_MERCHANT_ID, allEntries = true)
    })
    public boolean updateById(Buyer entity) {
        return retBool(baseMapper.updateById(entity));
    }

    @Override
    public Integer countBuyerNum(CountBuyerNumReq req) {
        return buyerMapper.countBuyerNum(req);
    }

    /**
     * 根据采购商名称查询, 相同时只返回一条
     *
     * @param buyerName
     * @return
     */
    @Override
    public Buyer fetchByName(String buyerName) {
        if (StrUtil.isEmpty(buyerName)) {
            return null;
        }
        return baseMapper.selectList(Wrappers.<Buyer>query().lambda()
                .eq(Buyer::getBuyerName, buyerName)
        ).stream()
                .findFirst().orElse(null);
    }

    @Override
    public Buyer fetchByTelephone(String telephone) {
        if (StrUtil.isEmpty(telephone)) {
            return null;
        }
        return baseMapper.selectList(Wrappers.<Buyer>query().lambda()
                .eq(Buyer::getTelephone, telephone)
        ).stream()
                .findFirst().orElse(null);
    }

    @Override
    public Buyer fetchByUid(String uid) {
        if (StrUtil.isEmpty(uid)) {
            return null;
        }
        return baseMapper.selectList(Wrappers.<Buyer>query().lambda()
                .eq(Buyer::getPassportId, uid)
        ).stream()
                .findFirst().orElse(null);
    }
}
